<template>
  <ul class="xitongYonghu" style="z-index: 1">
    <li class="xitongYonghu-top">
      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">
        <div class="operation-group">
          <el-button type="primary" @click="dialogFormVisible = true">
            <el-icon><Plus /></el-icon>添加
          </el-button>
          <el-button type="danger" @click="deleteTick">
            <el-icon><Delete /></el-icon>勾选删除
          </el-button>
        </div>
        <div class="search-group" style="display: flex;align-items: center;">
          <el-input
              v-model="searchAll"
              placeholder="请输入评价名称、描述等关键字"
              style="width: 300px;margin-right: 10px"
              clearable
              @keyup.enter="serchBtn"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button
              type="primary"
              @click="serchBtn"
              :loading="isSearching"
          >
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSerchbtn">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </ul>

      <!-- 添加课程对话框 -->
      <el-dialog v-model="dialogFormVisible" title="添加课程" width="600">
        <el-form :model="form2" label-width="80px">
          <el-form-item label="课程名称" required>
            <el-input v-model="form2.courseName" placeholder="请输入课程名称" />
          </el-form-item>
          
          <el-form-item label="课程简介">
            <el-input v-model="form2.courseDescription" 
              type="textarea" 
              rows="3" 
              placeholder="请输入课程简介" 
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="适用人群">
                <el-input v-model="form2.targetAudience" placeholder="请输入适用人群" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订阅须知">
                <el-input v-model="form2.subscriptionTerms" placeholder="请输入订阅须知" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="原始价格">
                <el-input-number 
                  v-model="form2.originalPrice" 
                  :precision="2" 
                  :step="0.1" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="折扣">
                <el-input-number 
                  v-model="form2.discount" 
                  :precision="2" 
                  :step="0.1" 
                  :min="0" 
                  :max="1" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程图片" required>
                <el-upload
                  :auto-upload="false"
                  ref="imageUploadRef"
                  :on-change="handleImageChange"
                  :before-upload="beforeUploadImg"
                  :show-file-list="false"
                  accept="image/*"
                  class="avatar-uploader"
                >
                  <div class="avatar-wrapper">
                    <img v-if="form2.courseImage" :src="form2.courseImage" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </div>
                  <div class="upload-tip">

                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="咨询师">
                <el-select v-model="form2.consultantId" placeholder="请选择咨询师" style="width: 100%">
                  <el-option
                    v-for="item in consultants"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程时长">
                <el-input v-model="form2.totalDuration" placeholder="请输入课程时长" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课件数">
                <el-input-number 
                  v-model="form2.numberOfMaterials" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%" 
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="有效期">
            <el-input v-model="form2.validityPeriod" placeholder="请输入课程有效期" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addFM">确认添加</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 修改课程对话框 -->
      <el-dialog v-model="xiugaiVisible" title="修改课程" width="600">
        <el-form :model="form2" label-width="80px">
          <el-form-item label="课程名称" required>
            <el-input v-model="form2.courseName" placeholder="请输入课程名称" />
          </el-form-item>
          
          <el-form-item label="课程简介">
            <el-input v-model="form2.courseDescription" 
              type="textarea" 
              rows="3" 
              placeholder="请输入课程简介" 
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="适用人群">
                <el-input v-model="form2.targetAudience" placeholder="请输入适用人群" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订阅须知">
                <el-input v-model="form2.subscriptionTerms" placeholder="请输入订阅须知" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="原始价格">
                <el-input-number 
                  v-model="form2.originalPrice" 
                  :precision="2" 
                  :step="0.1" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="折扣">
                <el-input-number 
                  v-model="form2.discount" 
                  :precision="2" 
                  :step="0.1" 
                  :min="0" 
                  :max="1" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程图片" required>
                <el-upload
                  :auto-upload="false"
                  ref="imageUploadRefForEdit"
                  :on-change="handleImageChangeForEdit"
                  :before-upload="beforeUploadImg"
                  :show-file-list="false"
                  accept="image/*"
                  class="avatar-uploader"
                >
                  <div class="avatar-wrapper">
                    <img v-if="form2.courseImage" :src="form2.courseImage" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </div>
                  <div class="upload-tip">

                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="咨询师">
                <el-select v-model="form2.consultantId" placeholder="请选择咨询师" style="width: 100%">
                  <el-option
                    v-for="item in consultants"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程时长">
                <el-input v-model="form2.totalDuration" placeholder="请输入课程时长" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课件数">
                <el-input-number 
                  v-model="form2.numberOfMaterials" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%" 
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="有效期">
            <el-input v-model="form2.validityPeriod" placeholder="请输入课程有效期" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="xiugaiVisible = false">取消</el-button>
            <el-button type="primary" @click="EditFM">确认修改</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 课程列表 -->
      <li>
        <el-table ref="tableRef" v-if="isShow" :data="itemsArr" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="courseId" label="ID" width="80" />
          <el-table-column prop="courseName" label="课程名称" width="120" />
          <el-table-column prop="courseDescription" label="课程简介" width="180" />
          <el-table-column prop="targetAudience" label="适用人群" width="120" />
          <el-table-column prop="subscriptionTerms" label="订阅须知" width="120" />
          <el-table-column prop="originalPrice" label="原价" width="100">
            <template #default="scope">
              ¥{{ scope.row.originalPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="discount" label="折扣" width="100">
            <template #default="scope">
              {{ (scope.row.discount * 100).toFixed(0) }}%
            </template>
          </el-table-column>

          <el-table-column prop="courseImage" label="课程图片" width="100">

            <template #default="scope">

              <el-image

                  style="width: 50px; height: 50px"

                  :src="scope.row.courseImage"

                  :preview-src-list="[scope.row.courseImage]"

                  fit="cover">

              </el-image>

            </template>

          </el-table-column>

          <el-table-column prop="consultantId" label="咨询师编号" width="100" />
          <el-table-column prop="totalDuration" label="课程总时长" width="100" />
          <el-table-column prop="numberOfMaterials" label="课件数" width="70" />
          <el-table-column prop="validityPeriod" label="有效期" width="70" />
          <el-table-column prop="favoriteCount" label="收藏量" width="70" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.courseId)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </li>

      <!-- 分页器 -->
      <li>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </li>
    </li>
  </ul>
</template>

<script setup>
import { computed, ref, onMounted ,watch} from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from 'axios'
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue'

// 控制添加课程对话框显示隐藏
const dialogFormVisible = ref(false)
// 控制修改课程对话框显示隐藏
const xiugaiVisible = ref(false)
// 控制课程列表显示隐藏
const isShow = ref(true)
// 搜索框输入内容
const searchAll = ref('') // 搜索关键字
const isSearching = ref(false) // 是否处于搜索状态

// 分页相关的响应式变量声明
const currentPage = ref(1)    // 当前页码
const pageSize = ref(5)       // 每页显示数量
const total = ref(0)          // 总条数
const itemsArr = ref([])      // 表格数据
const fmList = ref([])        // 分页数据

// 表单数据
const form2 = ref({
  courseName: "",
  courseDescription: "",
  targetAudience: "",
  learningOutcomes: "",
  subscriptionTerms: "",
  originalPrice: "",
  discount: "",
  courseImage: "",
  consultantId: "",
  totalDuration: "",
  numberOfMaterials: "",
  validityPeriod: "",
  studyCount: "",
  reviewCount: "",
  purchaseVolume: "",
  courseTypeId: ""
})

// 课程列表数据
const coursesList = ref([])
// 课程类型列表数据
const courseTypes = ref([])
// 咨询师列表数据
const consultants = ref([])

// 获取课程列表
const getcoursesList = async () => {
  try {
    // 清空选中状态
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    selectedRows.value = []

    const response = await axios.get('admin/courses/list', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (response.data.code === 200) {
      itemsArr.value = response.data.data.list
      total.value = response.data.data.total
      currentPage.value = response.data.data.pageNum
      pageSize.value = response.data.data.pageSize
      isShow.value = true
    } else {
      throw new Error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// // 获取课程类型列表
// const getCourseTypes = async () => {
//   try {
//     const response = await axios.get('http://localhost:8080/admin/courseTypes')
//     courseTypes.value = response.data.data
//   } catch (error) {
//     console.error('获取课程类型失败:', error)
//   }
// }
//
// // 获取咨询师列表
// const getConsultants = async () => {
//   try {
//     const response = await axios.get('http://localhost:8080/admin/consultants')
//     consultants.value = response.data.data
//   } catch (error) {
//     console.error('获取咨询师列表失败:', error)
//   }
// }

// 文件上传相关状态及数据
const imageUploaded = ref(false)
const imageFile = ref(null)

// 通用文件上传方法
const uploadFile = async (file, type) => {
  if (!file) return;
  const formData = new FormData();
  formData.append('file', file);
  try {
    const response = await axios.post('admin/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.code === 200) {
      form2.value.courseImage = response.data.msg;
      imageUploaded.value = true;
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    ElMessage.error('图片上传失败');
  }
}

// 图片文件选择变化时处理
const handleImageChange = (file) => {
  imageFile.value = file.raw;
  uploadFile(imageFile.value, 'image');
}

// 图片文件上传前验证
const beforeUploadImg = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  return true;
}

// 添加课程
const addFM = async () => {
  try {
    if (!form2.value.courseName) {
      ElMessage.error('课程名称不能为空')
      return
    }
    const response = await axios.post('admin/courses', form2.value)
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
      dialogFormVisible.value = false
      getcoursesList()
      // 重置表单
      form2.value = {
        courseId: null,
        courseName: '',
        courseDescription: '',
        targetAudience: '',
        learningOutcomes: '',
        subscriptionTerms: '',
        originalPrice: '',
        discount: '',
        courseImage: '',
        consultantId: '',
        totalDuration: '',
        numberOfMaterials: '',
        validityPeriod: '',
        studyCount: '',
        reviewCount: '',
        purchaseVolume: ''
      }
    }
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error('添加失败')
  }
}

// 修改课程
const EditFM = async () => {
  try {
    // 表单验证
    if (!form2.value.courseName) {
      ElMessage.error('课程名称不能为空')
      return
    }

    // 创建加载状态
    const loading = ElLoading.service({
      lock: true,
      text: '正在修改...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 构造请求数据
    const updateData = {
      courseId: form2.value.courseId, // 确保有课程ID
      courseName: form2.value.courseName,
      courseDescription: form2.value.courseDescription,
      targetAudience: form2.value.targetAudience,
      subscriptionTerms: form2.value.subscriptionTerms,
      originalPrice: form2.value.originalPrice,
      discount: form2.value.discount,
      courseImage: form2.value.courseImage,
      consultantId: form2.value.consultantId,
      totalDuration: form2.value.totalDuration,
      numberOfMaterials: form2.value.numberOfMaterials,
      validityPeriod: form2.value.validityPeriod
    }

    // 发送修改请求
    const response = await axios.put(
      `admin/courses/update/${form2.value.courseId}`,
      updateData
    )

    // 处理响应
    if (response.data.code === 200) {
      ElMessage.success('修改成功')
      xiugaiVisible.value = false
      // 重新获取列表数据
      await getcoursesList()
      // 重置表单
      form2.value = {
        courseId: null,
        courseName: '',
        courseDescription: '',
        targetAudience: '',
        subscriptionTerms: '',
        originalPrice: '',
        discount: '',
        courseImage: '',
        consultantId: '',
        totalDuration: '',
        numberOfMaterials: '',
        validityPeriod: ''
      }
    } else {
      throw new Error(response.data.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error(error.message || '修改失败，请稍后重试')
  } finally {
    // 关闭加载状态
    ElLoading.service().close()
  }
}

// 删除课程
const handleDelete = async (courseId) => {
  try {
    const result = await ElMessageBox.confirm('确定要删除该课程吗?', '提示', {
      type: 'warning'
    })
    if (result === 'confirm') {
      const response = await axios.delete(`admin/courses/delete/${courseId}`)
      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        getcoursesList()
      }
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('取消删除')
  }
}


// 添加在其他 ref 变量声明的地方
const selectedRows = ref([]) // 用于存储选中的行
const tableRef = ref(null)   // 用于获取表格实例
// 处理表格行选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 勾选删除课程
const deleteTick = async () => {
  try {
    // 检查是否有选中的行
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先勾选要删除的课程')
      return
    }

    // 获取选中行的课程ID
    const courseIds = selectedRows.value.map(row => row.courseId)

    // 显示确认对话框
    const confirmResult = await ElMessageBox.confirm(
        `确定要删除选中的 ${courseIds.length} 个课程吗？`,
        '批量删除提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    if (confirmResult === 'confirm') {
      // 发送批量删除请求
      const response = await axios.delete('admin/courses/batch', {
        data: {courseIds},
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (response.data.code === 200) {
        ElMessage.success('批量删除成功')
        // 清空选中状态
        if (tableRef.value) {
          tableRef.value.clearSelection()
        }
        selectedRows.value = [] // 清空选中数组
        await getcoursesList() // 重新获取列表数据
      } else {
        ElMessage.error(response.data.msg || '批量删除失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    // 确保在任何情况下都清空选中状态
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    selectedRows.value = []
  }
}


// 处理修改课程按钮点击事件
const handleEdit = (row) => {
  // 确保所有需要的字段都被正确赋值
  form2.value = {
    courseId: row.courseId,
    courseName: row.courseName || '',
    courseDescription: row.courseDescription || '',
    targetAudience: row.targetAudience || '',
    subscriptionTerms: row.subscriptionTerms || '',
    originalPrice: row.originalPrice || 0,
    discount: row.discount || 0,
    courseImage: row.courseImage || '',
    consultantId: row.consultantId || '',
    totalDuration: row.totalDuration || '',
    numberOfMaterials: row.numberOfMaterials || 0,
    validityPeriod: row.validityPeriod || ''
  }
  xiugaiVisible.value = true
}

// 分页相关，处理每页显示数量变化
const handleSizeChange = async (size) => {
  try {
    // 先清空选中状态
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    selectedRows.value = []

    pageSize.value = size
    currentPage.value = 1  // 切换每页数量时重置为第一页
    await getcoursesList()
  } catch (error) {
    console.error('切换页面大小失败:', error)
  }
}

// 分页相关，处理当前页码变化
const handleCurrentChange = async (page) => {
  try {
    // 先清空选中状态
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    selectedRows.value = []

    currentPage.value = page
    await getcoursesList()
  } catch (error) {
    console.error('切换页码失败:', error)
  }
}

// 搜索按钮点击事件
const serchBtn = async () => {
  try {
    // 设置搜索状态
    isSearching.value = true

    console.log('发送搜索请求，参数:', {
      keyword: searchAll.value,
      page: currentPage.value,
      pageSize: pageSize.value
    })

    const response = await axios.get('admin/courses/search', {
      params: {
        keyword: searchAll.value,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })

    console.log('搜索响应数据:', response.data)

    if (response.data.code === 200) {
      const {list, total: totalCount, pageNum, pageSize: size} = response.data.data

      // 更新数据
      itemsArr.value = list || []
      total.value = totalCount || 0
      currentPage.value = pageNum
      pageSize.value = size
      isShow.value = true

      // 显示搜索结果状态
      if (list && list.length > 0) {
        ElMessage.success(`找到 ${list.length} 条匹配记录`)
      } else {
        ElMessage.info('未找到匹配的课程')
      }
    } else {
      throw new Error(response.data.msg || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error(error.message || '搜索失败，请稍后重试')
  } finally {
    isSearching.value = false
  }
}

// 重置搜索按钮点击事件
const resetSerchbtn = async () => {
  try {
    // 重置所有状态
    searchAll.value = ''
    currentPage.value = 1
    pageSize.value = 5
    isSearching.value = false

    // 清空选中状态
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    selectedRows.value = []

    // 重新获取数据
    await getcoursesList()

    ElMessage.success('已重置')
  } catch (error) {
    console.error('重置失败:', error)
    ElMessage.error('重置失败，请稍后重试')
  }
}

// 监听分页变化
watch([currentPage, pageSize], async () => {
  if (isSearching.value && searchAll.value) {
    await serchBtn()
  } else {
    await getcoursesList()
  }
})

const filterByCourseType = (typeId) => {
  if (typeId === "") {
    getcoursesList();
    return;
  }
  itemsArr.value = coursesList.value.filter(course => course.courseTypeId === typeId);
  isShow.value = false;
}

// 假设页面上有一个下拉框用于选择课程类型来筛选，这里可以定义一个响应式数据来绑定下拉框的值
const selectedCourseTypeId = ref("");
// 监听下拉框值变化，触发筛选函数
watch(selectedCourseTypeId, (newValue) => {
  filterByCourseType(newValue);
});

// 再比如添加一个函数用于根据咨询师筛选课程列表
const filterByConsultant = (consultantId) => {
  if (consultantId === "") {
    getcoursesList();
    return;
  }
  itemsArr.value = coursesList.value.filter(course => course.consultantId === consultantId);
  isShow.value = false;
}

// 同样假设页面有对应咨询师选择的下拉框，定义响应式数据绑定其值
const selectedConsultantId = ref("");
watch(selectedConsultantId, (newValue) => {
  filterByConsultant(newValue);
});

// 可以添加一个函数用于批量设置课程的某个属性（比如批量设置折扣，这里只是示例，可按需修改具体逻辑）
const batchSetDiscount = async () => {
  const selectedRows = tableRef.value.getCheckedRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请先勾选要操作的课程');
    return;
  }
  const newDiscount = prompt('请输入要设置的折扣值');
  if (newDiscount === null) {
    return; // 用户取消输入
  }
  const courseId = selectedRows.map(row => row.courseId);
  try {
    const dataToSend = {
      courseId,
      newDiscount: parseFloat(newDiscount)
    };
    const response = await axios.delete('admin/courses/batch', {
      data: {courseId}
    });
    if (response.data.code === 200) {
      ElMessage.success('折扣设置成功');
      getcoursesList();
    } else {
      ElMessage.error(response.data.msg || '折扣设置失败');
    }
  } catch (error) {
    console.error('批量设置折扣出现异常:', error);
    ElMessage.error('批量设置折扣出现异常，请稍后重试');
  }
}

const handleImageChangeForEdit = (file) => {
  // 获取文件原始数据并赋值给对应的响应式变量，方便后续操作
  imageFileForEdit.value = file.raw;
  // 调用通用的文件上传函数进行文件上传，这里传入文件和类型标识，表明是图片文件上传
  uploadFile(imageFileForEdit.value, 'image');
};

// 还可以添加一些针对页面加载时的默认操作，比如默认加载课程列表、课程类型列表、咨询师列表等
onMounted(async () => {
  try {
    await getcoursesList()
  } catch (error) {
    console.error('初始化加载失败:', error)
    ElMessage.error('初始化加载失败')
  }
})

// 监听 itemsArr 的变化
watch(itemsArr, (newVal) => {
  console.log('itemsArr 发生变化:', newVal)
}, {deep: true})

</script>

<style scoped>
.xitongYonghu {
  padding: 20px;
  background-color: #ededed;
}
.avatar-uploader {
  text-align: center;
}

.avatar-wrapper {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  padding: 8px;
  margin-bottom: 8px;
  transition: border-color 0.3s;
}

.avatar-wrapper:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: left;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper),

:deep(.el-select__wrapper) {
  width: 100%;
}
</style>